package com.atguigu.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.exception.NoStockException;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitResponseVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;

    @GetMapping("/aliPayOrder")
    @ResponseBody
    public String aliPayOrder(String orderSn) throws AlipayApiException {
        PayVo payVo = orderService.getPayVoWithOrderSn(orderSn);
        String pay = alipayTemplate.pay(payVo);
        System.out.println(pay);
        return pay;
    }

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = orderService.toTrade();
        model.addAttribute("confirmOrderData",orderConfirmVo);
        return "confirm";
    }

    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) {
        OrderSubmitResponseVo orderSubmitResponseVo = null;
        try {
            orderSubmitResponseVo = orderService.submitOrder(orderSubmitVo);
            if(orderSubmitResponseVo.getCode()==0){
                redirectAttributes.addFlashAttribute("submitOrderResp",orderSubmitResponseVo);
                return "redirect:http://order.gulimall.com/pay.html";
            }
            String msg = "";
            switch (orderSubmitResponseVo.getCode()){
                case 1 : msg = "令牌过期，请重新下单";
                    break;
                case 2 : msg = "价格发生改变，请查看后重新下单";
                    break;
            }
            redirectAttributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.gulimall.com/toTrade";
        } catch (Exception e) {
            if(e instanceof NoStockException){
                redirectAttributes.addFlashAttribute("msg","库存不足");
            }
            return "redirect:http://order.gulimall.com/toTrade";
        }

    }

    @GetMapping("/pay.html")
    public String pay(){
        return "pay";
    }

}
